from venv import logger

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import xlwt
from loguru import logger


browser = webdriver.Chrome()
browser.set_window_size(1400,900)

book = xlwt.Workbook(encoding='utf-8', style_compression=0)

sheet = book.add_sheet('蔡徐坤篮球',cell_overwrite_ok=True)
sheet.write(0, 0, '名称')
sheet.write(0, 1, '地址')
sheet.write(0, 2, '描述')
sheet.write(0, 3, '观看次数')
sheet.write(0, 4, '弹幕数')
sheet.write(0, 5, '发布时间')
n = 1

def search():
    try:
        logger.info('开始访问b站....')
        browser.get('https://www.bilibili.com/')

        #

        input = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR,
                 '#nav-searchform > div.nav-search-content > input'))
        )
        submit = WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable(
                (By.CSS_SELECTOR,
                 '#nav-searchform > div.nav-search-btn'))
        )



        input.send_keys('蔡徐坤 篮球')
        submit.click()

        logger.info('跳转到新窗口')
        all_h = browser.window_handles # 搜索后有两个窗口，一个主页，一个搜索后的页面
        browser.switch_to.window(all_h[1]) # 切换到搜索后的页面
        # get_source()

        total = WebDriverWait(browser,10).until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR,
                 "#all-list > div.flow-loader > div.page-wrap > div > ul > li.page-item.last > button"))
        )
        return int(total.text)
    except TimeoutException:
        return search()

search()
#
# def next_page(page_num):
#     pass
#
# def save_to_excel(soup):
#     pass
#
# def get_source():
#     pass
#
# def main():
#     try:
#         total = search()
#         print(total)
#
#         # for i in range(2, int(total+1)):
#         #     next_page(i)
#     finally:
#         browser.close()
#
#
#
# if __name__ =='__main__':
#     main()
#     book.save('蔡徐坤篮球.xlsx')
#
#
# def get_total_pages():
#     total = WAIT.until(EC.presence_of_element_located(By.CSS_SELECTOR, "#server-search-app > div.contain > div.body-contain > div > div.page-wrap > div > ul > li.page-item.last > button"))
#     return int(total.text)
#
#
